import axios from "axios";
import Vue from "vue";
import router from "./../router"

const http = axios.create({
    baseURL: "http://localhost:3000"
})

// Add a request interceptor 请求拦截器
http.interceptors.request.use(function (config) {
    // Do something before request is sent
    if (localStorage.token) {
        config.headers.Authorization = 'Bearer ' + localStorage.token;
    }
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

//响应拦截器
http.interceptors.response.use(res => {
    console.log(res);
    return res;
}, function (err) {
    console.log(err);
    if (err.response.data.message) {
        Vue.prototype.$message({
            type: 'error',
            message: err.response.data.message
        })
    }
    if(err.status === 402 || 401){
        console.log(err.response);
        router.push("/login");
    }
    // console.log(err.response.data.message);
    //$message 是element-ui 挂载上去的
    // console.log(err);
    return Promise.reject(err)
})

export default http